//
//  Encryption.swift
//  encryption
//
//  Created by 大姚 on 2017/8/30.
//  Copyright © 2017年 YY. All rights reserved.
//

import CryptoSwift

class Encryption: NSObject {
    //key的bytes数组位数来进行AES128/192/256加密.
    //key -> 加密方式
    //16  -> AES128
    //24  -> AES192
    //32  -> AES256
    /*
    填充方式:
    - parameters:
    - noPadding
    - zeroPadding
    - pkcs7
    - pkcs5
    加密模式:
    - CBC
    — CTR
    - OFB
    - CFB
    - ECB
    */
    //iv:偏移量，加密过程中会按照偏移量进行循环位移
    static let key = "ezyform-encrypt-"//"hYYvesbdjcdlcVUp"
    
    //MARK: AES-ECB128加密
    public static func Endcode_AES_ECB(strToEncode:String)->String {
        // 从String 转成data
        let data = strToEncode.data(using: String.Encoding.utf8)
        
        // byte 数组
        var encrypted: [UInt8] = []
        do {
            let aes = try AES(key: Array(key.utf8), blockMode: ECB(), padding: .pkcs5)
            encrypted = try aes.encrypt(data!.bytes)
        } catch let e {
            print(e.localizedDescription)
        }
        
        let encoded =  Data(encrypted)
        return self.convertByte(bytedata: encoded)
    }
    //MARK: Data转Base64URL加密,处理成URL safe模式，+和/在URL中是特殊字符串需要处理
    internal class func convertByte(bytedata:Data?) -> String {
        guard let bytedata = bytedata else {
            return ""
        }
        // data数据进行base64加密
        var result = bytedata.base64EncodedString()
        // +替换为—
        result = result.replacingOccurrences(of: "+", with: "-")
        // /替换为_
        result = result.replacingOccurrences(of: "/", with: "_")
        return result
    }
    //MARK: 后台反回的base64字符串转为data
    internal class func convertBase64URL(base64:String?) -> Data? {
        guard let base64 = base64 else {
            return nil
        }
        // -替换为+
        let base64Str = base64.replacingOccurrences(of: "-", with: "+")
        // _替换为/
        let base64Str2 = base64Str.replacingOccurrences(of: "_", with: "/")
        var base64Str3 = ""
        // =号补全
        let mod4 = base64Str.count % 4
        if mod4 > 0 {
            let appStr = ("====" as NSString).substring(to: (4 - mod4))
            base64Str3 = base64Str2 + appStr
        }
        // base64Str转data并进行Base64Decoding
        return Data(base64Encoded: base64Str3, options: Data.Base64DecodingOptions.init(rawValue: 0))
    }
}
